package com.zzh.myapplication.activity;

import android.app.AlertDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import net.icarplus.car.R;
import net.icarplus.car.bean.AttachChargeItemBean;
import net.icarplus.car.bean.CarInfo;
import net.icarplus.car.bean.DepositChargeItemBean;
import net.icarplus.car.bean.ExpenseBean;
import net.icarplus.car.bean.OrderBillingDetailBean;
import net.icarplus.car.constant.UrlValues;
import net.icarplus.car.datedialog.DateTimePicker;
import net.icarplus.car.manager.BaseActivity;
import net.icarplus.car.popuwindpw.ShowPopuWindow;
import net.icarplus.car.service.PublicRequest;
import net.icarplus.car.tools.LoadingUtil;
import net.icarplus.car.tools.S;
import net.icarplus.car.tools.SPUtils;
import net.icarplus.car.tools.T;
import net.icarplus.car.tools.ToolBarHelper;
import net.icarplus.car.tools.UserUtils;
import net.icarplus.car.views.PasswordInputView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;


/**
 * 项目名称：icarplus-car-android
 * 类描述：
 * 创建人：Gophy
 * 创建时间：16/3/12 17:52
 * 修改人：Gophy
 * 修改时间：16/3/12 17:52
 * 修改备注：
 */
public class DivideTimeCarListDetailActivity extends BaseActivity implements View.OnClickListener {

    private Button btnSubmit;
    private ImageView ivSwitch;
    private ImageView ivCkNonDeductible;
    private boolean isNonDeductiblle = false;
    private boolean isCheck = false;
    private Toolbar toolbar;
    private SimpleDraweeView ivBigCar;
    private RelativeLayout rl_get_car_time;
    private TextView takeCarTimeTxt;
    private Calendar mDate = Calendar.getInstance();
    private PopupWindow popupWindow;
    private DateTimePicker mDateTimePicker;
    private long time;//时间选择器回调
    private String timeString_t = "";
    private String nowTimeString = "";//校验用，当前时间
    private LoadingUtil loadingUtil;
    private String rentPrice;
    private String mileagePrice;
    private String nonDeductiblePrice;
    private String depositPrice;
    private TextView tv_car_depost_money;
    private TextView tv_non_deductible_money;
    private TextView tv_per_km;
    private TextView tv_per_min;
    private TextView tv_total_money_info;
    private String depositChargeItems;
    private String attachChargeItems;
    CarInfo carInfo = null;
    private int money;
    private AlertDialog.Builder builder;
    PasswordInputView mView;
    AlertDialog _cardialog;
    String ordermoney = "";
    ShowPopuWindow popeWindow = new ShowPopuWindow();
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 100:
                    builder = new AlertDialog.Builder(DivideTimeCarListDetailActivity.this);
                    View carview = View.inflate(DivideTimeCarListDetailActivity.this, R.layout.dialog_submit_failure, null);
                    builder.setView(carview);
                    _cardialog = builder.show();
                    new Thread() {
                        @Override
                        public void run() {
                            super.run();
                            try {
                                Thread.sleep(10000);
                                _cardialog.dismiss();
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                    }.start();
                    break;
                case 1000:
                    DivideTimeCarListDetailActivity.this.loadingUtil.stopShowLoading();
                    Log.e("1000", msg.obj.toString());
                    //refreshCarList(msg.obj.toString());
                    break;
                case 2000:
                    DivideTimeCarListDetailActivity.this.loadingUtil.stopShowLoading();
                    if (msg.obj.toString() != null) {
                        Gson gson = new Gson();
                        ExpenseBean result = gson.fromJson(msg.obj.toString(),
                                new TypeToken<ExpenseBean>() {
                                }.getType());
                        OrderBillingDetailBean orderBillingDetailBean = result.orderBillingDetail;
                        //里程费
                        mileagePrice = orderBillingDetailBean.priceUnitDesc;
                        String[] mileage = mileagePrice.split("\\,");
                        tv_per_km.setText(mileage[1]);
                        //getIntent().getStringExtra("unitPrice")
                        tv_per_min.setText(mileage[0]);
                        List<DepositChargeItemBean> depositChargeItemBeans = new ArrayList<DepositChargeItemBean>();
                        List<AttachChargeItemBean> attachChargeItemBeans = new ArrayList<AttachChargeItemBean>();
                        depositChargeItemBeans = orderBillingDetailBean.depositChargeItems;
                        attachChargeItemBeans = orderBillingDetailBean.attachChargeItems;
                        DepositChargeItemBean mDepositChargeItemBean = null;
                        AttachChargeItemBean attachChargeItemBean = null;
                        for (int i = 0; i < depositChargeItemBeans.size(); i++) {
                            mDepositChargeItemBean = depositChargeItemBeans.get(i);
                            // 押金
                            tv_car_depost_money.setText(mDepositChargeItemBean.price);
                            depositChargeItems = mDepositChargeItemBean.price;
                        }
                        for (int i = 0; i < attachChargeItemBeans.size(); i++) {
                            attachChargeItemBean = attachChargeItemBeans.get(i);
                            tv_non_deductible_money.setText(attachChargeItemBean.price);
                            attachChargeItems = attachChargeItemBean.price;
                        }
                        money = Integer.parseInt(depositChargeItems) + Integer.parseInt(attachChargeItems);
                        ordermoney = money + "";
                        tv_total_money_info.setText(ordermoney);
                    }

                    break;
                case 200:
                    System.out.print("200" + msg.obj.toString());
                    if (msg.obj.toString() != null) {
                        try {
                            JSONObject jsonObject = new JSONObject(msg.obj.toString());
                            String appNo = jsonObject.optString("appNo");
                            Intent intent = new Intent(DivideTimeCarListDetailActivity.this, OrderPayCenterActivity.class);
                            intent.putExtra("depositChargeItems", ordermoney);
                            intent.putExtra("appno", appNo);
                            intent.putExtra("licenseNo", carInfo.licenseNo);
                            start_Activity(intent);

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                    break;
                case 3000:
                    Log.e("3000", "3000000");
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    public void setContent() {
        setContentView(R.layout.activity_divide_time_car_list_detail);
    }

    @Override
    public void initComponent() {
        btnSubmit = (Button) findViewById(R.id.btn_submit);
        ivSwitch = (ImageView) findViewById(R.id.iv_use_car_reason);
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        ivBigCar = (SimpleDraweeView) findViewById(R.id.iv_car_name);
        ivCkNonDeductible = (ImageView) findViewById(R.id.iv_ck_non_deductible);
        rl_get_car_time = (RelativeLayout) findViewById(R.id.rl_get_car_time);
        takeCarTimeTxt = (TextView) findViewById(R.id.tv_get_car_time);
        tv_car_depost_money = (TextView) findViewById(R.id.tv_car_depost_money);
        tv_non_deductible_money = (TextView) findViewById(R.id.tv_non_deductible_money);
        tv_per_km = (TextView) findViewById(R.id.tv_per_km);
        tv_per_min = (TextView) findViewById(R.id.tv_per_min);
        tv_total_money_info = (TextView) findViewById(R.id.tv_total_money_info);
        loadingUtil = new LoadingUtil(this, getString(R.string.loading_text));
    }

    @Override
    public void setListener() {
        btnSubmit.setOnClickListener(this);
        ivSwitch.setOnClickListener(this);
        ivCkNonDeductible.setOnClickListener(this);
        rl_get_car_time.setOnClickListener(this);
    }

    @Override
    public void onAfterInit() {
        ToolBarHelper.setNormalTitleAndBack(this, toolbar, getIntent().getStringExtra("title"));
        ivBigCar.setImageURI(Uri.parse(getIntent().getStringExtra("picUrl")));
        this.loadingUtil.startShowLoading();
        getAmtData();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_submit:
                this.loadingUtil.startShowLoading();
                reqNetSubmitOrder();
                break;
            case R.id.iv_use_car_reason:
                if (!isCheck) {
                    ivSwitch.setImageResource(R.mipmap.icon_check_no);
                    isCheck = true;
                } else {
                    ivSwitch.setImageResource(R.mipmap.icon_check_yes);
                    isCheck = false;
                }
                break;
            case R.id.iv_ck_non_deductible:
                if (!isNonDeductiblle) {
                    ivCkNonDeductible.setImageResource(R.mipmap.icon_check_no);
                    isNonDeductiblle = true;
                    tv_total_money_info.setText(depositChargeItems);
                } else {
                    ivCkNonDeductible.setImageResource(R.mipmap.icon_check_yes);
                    isNonDeductiblle = false;
                    money = Integer.parseInt(depositChargeItems) + Integer.parseInt(attachChargeItems);
                    tv_total_money_info.setText(money + "");
                }
                break;
            case R.id.rl_get_car_time:
                popeWindow.showTimePop(this, v, 0, new ShowPopuWindow.onSelectTimeString() {
                    @Override
                    public void onTimeString(String timeString) {
                        takeCarTimeTxt.setText(timeString);
                        timeString_t = timeString;
                    }
                });
                break;
            default:
                break;
        }

    }

    private void getAmtData() {
        JSONObject json = new JSONObject();
        if (DivideTimeCarActivity.carResultInfo != null) {
            List<CarInfo> list = DivideTimeCarActivity.carResultInfo.queryList;
            for (int i = 0; list != null && i < list.size(); i++) {
                carInfo = list.get(i);
            }
            try {
                //new String(licenseNo.getBytes("UTF-8"))
                String licenseNo = carInfo.licenseNo;
                json.put("autoModelNo", carInfo.autoModelNo);
                json.put("licenseNo", licenseNo);
                json.put("rentType", "01");
            } catch (JSONException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
            System.out.println("url:" + UrlValues.RENTCAR_PREPAY_AMT_URL + " Amt params:" + json.toString());
            PublicRequest.customMainRequestPost(this, UrlValues.RENTCAR_PREPAY_AMT_URL, handler, json);
        }
    }

    JSONObject customJson;

    private void reqNetSubmitOrder() {
        boolean isLogin = SPUtils.getBoolean(this, "isLogin", false);
        String userPhone = SPUtils.getString(this, "LoginInfo", "");
        if (!isLogin || S.isEmpty(userPhone)) {
            UserUtils.cleanUserInfo(this);
            T.showShort("请先登录！");
            Intent intent = new Intent(DivideTimeCarListDetailActivity.this, LoginActivity.class);
            start_Activity(intent);
            return;
        }
        customJson = new JSONObject();
        JSONObject listJson = new JSONObject();
        JSONArray arrays = new JSONArray();
        try {
            listJson.put("chargeItemCode", "0");
            listJson.put("itemName", "");
//          istJson.put("needFlag", "");
            listJson.put("chosenFlag", "0");
            arrays.put(listJson);
            customJson.put("prcChargeDetList", arrays);
            customJson.put("mobile", userPhone);
            customJson.put("licenseNo", getIntent().getStringExtra("licenseNo"));
            customJson.put("orderMode", "01");
            customJson.put("rentType", "01");
            customJson.put("isBusiness", "0");
            customJson.put("userReason", "");
            customJson.put("pttrcTime", timeString_t);
            customJson.put("prtrcTime", "");
            customJson.put("qcRtNo", "");
            customJson.put("hcRtNo", "");

        } catch (JSONException e) {
            e.printStackTrace();
        }
        Log.e("customJson", customJson.toString());
        Log.e("submit_rent_order_url", UrlValues.SUBMIT_RENT_ORDER_URL);
//        PublicRequest.customMainRequestPost(this, UrlValues.SUBMIT_RENT_ORDER_URL, handler, customJson);
        PublicRequest.doPostRequest(UrlValues.SUBMIT_RENT_ORDER_URL, handler, customJson, 200, 100);
    }

}
